from socket import *
from time import ctime, sleep
import threading

class UDP_auth:
    def __init__(self):
        # 全局参数配置
        self.encoding = "utf-8"  # 使用的编码方式
        self.broadcastPort = 7789   # 广播端口

        # 创建广播接收器
        self.recvSocket = socket(AF_INET, SOCK_DGRAM)
        self.recvSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.recvSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        self.recvSocket.bind(('', self.broadcastPort))

        # 创建广播发送器
        self.sendSocket = socket(AF_INET, SOCK_DGRAM)
        self.sendSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

        # 其他
        self.threads = []

    def send(self):
        """发送广播"""
        print("请求认证...")
        self.sendSocket.sendto("***请求认证".encode(self.encoding), ('255.255.255.255', self.broadcastPort))
        
        while True:
            sendData = input("please input auth or exit:")

            self.sendSocket.sendto(sendData.encode(self.encoding), ('255.255.255.255', self.broadcastPort))
            # print("【%s】%s:%s" % (ctime(), "我", sendData))
            if sendData == 'exit':
                break
            sleep(1)

    def recv(self,authentication):
        """接收广播"""

        print("启动认证...")
        while True:
            # 接收数据格式：(data, (ip, port))
            recvData = self.recvSocket.recvfrom(1024)
            if recvData[0].decode(self.encoding) == 'exit':
                break
            else:
                if authentication:
                    print("【%s】[%s : %s] : Authentication Successed!!" % (ctime(), recvData[1][0], recvData[1][1]))
                else:
                    print("【%s】[%s : %s] : Authentication Unsuccessed!!" % (ctime(), recvData[1][0], recvData[1][1]))
            sleep(1)
    
    
    def stop_thread(thread):
        _async_raise(thread.ident, SystemExit)
        
        
    def start_rec(self,auth):
        """启动线程"""

        t1 = threading.Thread(target=self.recv(auth))
        self.threads.append(t1)
        
        if recvData[0].decode(self.encoding) == 'exit':
            stop_thread(t1)
        for t in self.threads:
            t.setDaemon(True)
            t.start()

        while True:
            pass
if __name__ == "__main__":
    demo = UDP_auth()
    demo.send()